package com.flnet.spsys.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;

import lombok.Getter;
import lombok.Setter;


@Getter
@Setter
@Component
public class OssUtils {


    @Value("${oss.accessKeyId}")
    public String accessKeyId;

    @Value("${oss.accessKeySecret}")
    public String accessKeySecret;

    @Value("${oss.endpoint}")
    public String endpoint;

    @Value("${oss.bucketName}")
    public String bucketName;

    public static OSSClient client;
    public  OSSClient initClient(){
        if(null==client){
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(5000);
            conf.setMaxErrorRetry(10);
            client = new OSSClient("http://" + endpoint, accessKeyId, accessKeySecret,conf);
        }
        return client;
    }


    /**
     * 上传文件
     *
     * @param fileKey
     * @param content
     * @throws FileNotFoundException
     */
    public boolean putObjectForInputStream(String fileKey, InputStream content) {
        if (null == fileKey || "" == fileKey.trim())
            return false;
        try {
            initClient();
            ObjectMetadata meta = new ObjectMetadata();
            client.putObject(bucketName, fileKey, content, meta);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 上传图片
     * @param imageName
     * @param content
     * @param if400
     * @throws FileNotFoundException
     */
    public String putObjectForImage(String imageName, InputStream content, boolean if400) {
        if (null == imageName || "" == imageName.trim())
            return null;
        try {
            String file = "images/" + imageName.substring(0, imageName.indexOf(".")) + "/" + imageName;
            putObjectForInputStream(file,content);
            return "http://"+bucketName+"."+endpoint+"/"+file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public String getObject(String key) {
        try {
            OSSObject object = client.getObject(bucketName, key);
            InputStream objectContent = object.getObjectContent();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i = -1;
            while ((i = objectContent.read()) != -1) {
                baos.write(i);
            }
            objectContent.close();
            return baos.toString("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
